package game.views;

import haxe.Timer;
import hx.display.ListView;
import hx.core.Hxmaker;
import game.shader.CosQuickShader;
import game.data.GameData;
import game.shader.CosShader;
import hx.utils.SoundManager;
import hx.display.DisplayObjectRecycler;
import hx.display.ArrayCollection;
import motion.Actuate;
import hx.events.Keyboard;
import hx.events.KeyboardEvent;
import hx.assets.BitmapDataFuture;
import hx.display.BitmapData;
import hx.events.Event;
import hx.ui.UIManager;
import game.data.XlsData;
import hx.display.UILoadScene;

/**
 * 角色选择界面
 */
@:build(hx.macro.UIBuilder.build("assets/views/RoleSelectView.xml"))
class RoleSelectView extends UILoadScene {
	/**
	 * 当角色选择完毕后
	 */
	public var onRoleSelected:Array<Dynamic>->Void;

	/**
	 * 是否允许2P角色选择
	 */
	public var selected2pEnabled:Bool = true;

	override function onLoaded() {
		super.onLoaded();
		this.close.clickEvent = () -> {
			this.replaceScene(new StartView(), true);
		}
		this.p2bar.selected.data = UIManager.getBitmapData("select2p");
		this.p2bar.selected_ok.data = UIManager.getBitmapData("2p_ok");
		this.updateLayout();

		// 侦听角色选择
		this.p1bar.addEventListener(Event.CHANGE, onRoleChange);
		this.p2bar.addEventListener(Event.CHANGE, onRoleChange);

		if (!selected2pEnabled) {
			this.unuse2p.visible = true;
			this.p2bar.alpha = 0.5;
			this.p2nameBox.alpha = 0.5;
			this.p2role.alpha = 0.5;
			this.p2tags.alpha = 0.5;
			this.p2attr4.alpha = 0.5;
			this.p2groups.alpha = 0.5;
		} else {
			this.btn_select.visible = false;
			this.unuse2p.visible = false;
		}

		btn_select.clickEvent = () -> {
			p1bar.lock();
			onRoleSelectedCheck();
			this.p1groups.mouseEnabled = false;
		}

		// 分类生成
		var groups:Array<{
			name:String,
			roles:Array<Dynamic>
		}> = [
			{
				name: "全部",
				roles: XlsData.roles.data.filter((f) -> GameData.getInstance().isUnlockRole(f.roleid))
			}
			];
		var groupsKey = [];
		for (item in XlsData.roles.data) {
			// 这里要判断是否解锁
			if (!GameData.getInstance().isUnlockRole(item.roleid)) {
				continue;
			}
			if (groupsKey.indexOf(item.group) == -1) {
				groupsKey.push(item.group);
			}
		}
		for (key in groupsKey) {
			groups.push({
				name: key,
				roles: XlsData.roles.getDataArrayByGroup(key).filter((f) -> GameData.getInstance().isUnlockRole(f.roleid))
			});
		}
		// 生成系列列表
		this.p1groups.data = new ArrayCollection(groups);
		this.p1groups.itemRendererRecycler = DisplayObjectRecycler.withClass(RoleGroupButton);
		this.p2groups.data = new ArrayCollection(groups);
		this.p2groups.itemRendererRecycler = DisplayObjectRecycler.withClass(RoleGroupButton);
		this.p1groups.addEventListener(Event.CHANGE, (e) -> {
			// 更换1P的角色列表
			if (this.p1groups.selectedItem != null) {
				this.p1bar.setRolesData(this.p1groups.selectedItem.roles);
				this.p1bar.setSelectIndex(-1);
				SoundManager.getInstance().playEffect("move_select");
				updateRoleGroupButtonLight(this.p1groups);
			} else {
				updateRoleGroupButtonLight(this.p1groups, false);
			}
		});
		this.p2groups.addEventListener(Event.CHANGE, (e) -> {
			// 更换2P的角色列表
			if (this.p2groups.selectedItem != null) {
				this.p2bar.setRolesData(this.p2groups.selectedItem.roles, true);
				this.p2bar.setSelectIndex(-1);
				SoundManager.getInstance().playEffect("move_select");
				updateRoleGroupButtonLight(this.p2groups);
			} else {
				updateRoleGroupButtonLight(this.p2groups, false);
			}
		});
		this.p1groups.selectedIndex = 0;
		this.p2groups.selectedIndex = 0;
		this.p1bar.setSelectIndex(0);
		this.p2bar.setSelectIndex(0);
		this.updateEnabled = true;
		this.animte_bg.shader = CosShader.getInstance();
		this.keyTips.verticalAlign = MIDDLE;
		Timer.delay(() -> {
			updateRoleGroupButtonLight(this.p1groups);
			updateRoleGroupButtonLight(this.p2groups);
		}, 16);
	}

	public function updateRoleGroupButtonLight(listview:ListView, isLight:Bool = true):Void {
		for (object in listview.children) {
			var itemRenderer = listview.getChildAt(listview.selectedIndex);
			if (object == itemRenderer) {
				cast(object, RoleGroupButton).setGroupLight(isLight);
			} else {
				cast(object, RoleGroupButton).setGroupLight(false);
			}
		}
	}

	override function onUpdate(dt:Float) {
		super.onUpdate(dt);
		CosShader.getInstance().update(dt);
		CosQuickShader.getInstance().update(dt);
		this.setDirty();
	}

	override function onAddToStage() {
		super.onAddToStage();
		this.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
	}

	override function onRemoveToStage() {
		super.onRemoveToStage();
		this.stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
	}

	/**
	 * 检查所有玩家是否已经选择了角色
	 */
	private function onRoleSelectedCheck():Void {
		if (selected2pEnabled) {
			if (this.p1bar.isLock && this.p2bar.isLock) {
				this.onRoleSelected([this.p1bar.currentSelectedItem?.data, this.p2bar.currentSelectedItem?.data]);
			}
		} else if (this.p1bar.isLock) {
			this.onRoleSelected([this.p1bar.currentSelectedItem?.data]);
		}
	}

	private function onKeyDown(e:KeyboardEvent):Void {
		switch e.keyCode {
			case Keyboard.J:
				// 确定
				this.p1bar.lock();
				onRoleSelectedCheck();
				this.p1groups.mouseEnabled = false;
			case Keyboard.K:
				// 取消
				this.p1bar.unlock();
				this.p1groups.mouseEnabled = true;
			case Keyboard.NUMBER_1, Keyboard.NUMPAD_1:
				// 确定
				if (!selected2pEnabled)
					return;
				this.p2bar.lock();
				onRoleSelectedCheck();
				this.p2groups.mouseEnabled = false;
			case Keyboard.NUMBER_2, Keyboard.NUMPAD_2:
				// 取消
				if (!selected2pEnabled)
					return;
				this.p2bar.unlock();
				this.p2groups.mouseEnabled = true;
			case Keyboard.A:
				// 左
				if (this.p1bar.selectedIndex == 0 || this.p1bar.selectedIndex == 7) {
					this.p1bar.setSelectIndex(-1);
					SoundManager.getInstance().playEffect("move_select");
				} else {
					this.p1bar.indexTurn(-1);
				}
			case Keyboard.D:
				// 右
				this.p1bar.indexTurn(1);
			case Keyboard.W:
				// 上
				if (this.p1bar.selectedIndex >= 0)
					this.p1bar.indexTurn(-7);
				else {
					if (this.p1groups.selectedIndex > 0) {
						this.p1groups.selectedIndex = this.p1groups.selectedIndex - 1;
					} else {
						this.p1groups.selectedIndex = this.p1groups.data.source.length - 1;
					}
				}
				this.p1groups.scrollToCurrentSelectedItem();
			case Keyboard.S:
				// 下
				if (this.p1bar.selectedIndex >= 0)
					this.p1bar.indexTurn(7);
				else {
					// 更新系列
					if (this.p1groups.selectedIndex < this.p1groups.data.source.length - 1) {
						this.p1groups.selectedIndex = this.p1groups.selectedIndex + 1;
					} else {
						this.p1groups.selectedIndex = 0;
					}
				}
				this.p1groups.scrollToCurrentSelectedItem();
			case Keyboard.LEFT:
				// 左
				if (!selected2pEnabled)
					return;
				this.p2bar.indexTurn(1);
			case Keyboard.RIGHT:
				// 右
				if (!selected2pEnabled)
					return;
				if (this.p2bar.selectedIndex == 0 || this.p2bar.selectedIndex == 7) {
					this.p2bar.setSelectIndex(-1);
					SoundManager.getInstance().playEffect("move_select");
				} else {
					this.p2bar.indexTurn(-1);
				}
			case Keyboard.UP:
				// 上
				if (!selected2pEnabled)
					return;
				if (this.p2bar.selectedIndex >= 0)
					this.p2bar.indexTurn(-7);
				else {
					if (this.p2groups.selectedIndex > 0) {
						this.p2groups.selectedIndex = this.p2groups.selectedIndex - 1;
					} else {
						this.p2groups.selectedIndex = this.p2groups.data.source.length - 1;
					}
					this.p2groups.scrollToCurrentSelectedItem();
				}
			case Keyboard.DOWN:
				// 下
				if (!selected2pEnabled)
					return;
				if (this.p2bar.selectedIndex >= 0)
					this.p2bar.indexTurn(7);
				else {
					// 更新系列
					if (this.p2groups.selectedIndex < this.p2groups.data.source.length - 1) {
						this.p2groups.selectedIndex = this.p2groups.selectedIndex + 1;
					} else {
						this.p2groups.selectedIndex = 0;
					}
				}
				this.p2groups.scrollToCurrentSelectedItem();
		}
	}

	private var __p1data:Dynamic;

	private var __p2data:Dynamic;

	/**
	 * 当角色选择发生变化时
	 * @param e 
	 */
	private function onRoleChange(e:Event):Void {
		var p1data = XlsData.roles.ofType(this.p1bar.currentSelectedItem?.data);
		var p2data = XlsData.roles.ofType(this.p2bar.currentSelectedItem?.data);
		this.p1name.data = p1data != null ? p1data.name : "请选择角色";
		this.p2name.data = p2data != null ? p2data.name : "请选择角色";
		this.p1author.data = p1data != null ? "贡献者：" + p1data.author : "";
		this.p2author.data = p2data != null ? "贡献者：" + p2data.author : "";
		if (p1data != null) {
			this.p1tags.setData(p1data.tags.split(","));
		} else {
			this.p1tags.setData(null);
		}
		if (p2data != null) {
			this.p2tags.setData(p2data.tags.split(","), true);
		} else {
			this.p2tags.setData(null);
		}
		if (__p1data != p1data) {
			// 更新能力值
			if (p1data == null)
				p1attr4.show(0, 0, 0, 0);
			else
				p1attr4.show(Std.parseFloat(p1data.bursts) / 5, Std.parseFloat(p1data.live) / 5, Std.parseFloat(p1data.motor) / 5,
					(5 - Std.parseFloat(p1data.difficulty)) / 5);
			Actuate.tween(this.p1role, 0.25, {x: -1000, alpha: 0}).onComplete(function() {
				if (p1data != null) {
					new BitmapDataFuture("assets/icons/roles/" + p1data.roleid + ".png").onComplete(bitmapData -> {
						if (p1data == __p1data) {
							this.p1role.data = bitmapData;
							Actuate.tween(this.p1role, 0.5, {x: 0, alpha: 1});
							this.updateLayout();
						}
					});
				} else {
					this.p1role.data = UIManager.getBitmapData("none");
					Actuate.tween(this.p1role, 0.5, {x: 0, alpha: 1});
				}
			});
		}
		if (__p2data != p2data) {
			if (p2data == null)
				p2attr4.show(0, 0, 0, 0);
			else
				p2attr4.show(Std.parseFloat(p2data.bursts) / 5, Std.parseFloat(p2data.live) / 5, Std.parseFloat(p2data.motor) / 5,
					(5 - Std.parseFloat(p2data.difficulty)) / 5);
			Actuate.tween(this.p2role, 0.25, {x: -1000, alpha: 0}).onComplete(function() {
				if (p2data != null)
					new BitmapDataFuture("assets/icons/roles/" + p2data.roleid + ".png").onComplete(bitmapData -> {
						if (p2data == __p2data) {
							this.p2role.data = bitmapData;
							Actuate.tween(this.p2role, 0.5, {x: 0, alpha: this.selected2pEnabled ? 1 : 0.5});
							this.updateLayout();
						}
					});
				else {
					this.p2role.data = UIManager.getBitmapData("none");
					Actuate.tween(this.p2role, 0.5, {x: 0, alpha: 1});
				}
			});
		}
		__p1data = p1data;
		__p2data = p2data;
		this.updateLayout();
	}

	override function updateLayout() {
		super.updateLayout();
		if (this.p1role != null) {
			this.p1role.height = Hxmaker.engine.stageHeight - 483;
			this.p2role.height = Hxmaker.engine.stageHeight - 483;
			this.p1role.scaleX = this.p1role.scaleY;
			this.p2role.scaleX = this.p2role.scaleY;
		}
	}
}
